package com.itboye.sunsun.shop.ui;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.sunsun.R;
import com.itboye.sunsun.adapter.ShopCarAdapter;
import com.itboye.sunsun.beans.ShopCarBean;
import com.itboye.sunsun.buy.ui.QueRenDingDan;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.custome.XListView;
import com.itboye.sunsun.custome.XListView.IXListViewListener;
import com.itboye.sunsun.dialog.WaitDialog;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.utils.DoubleParse;
import com.itboye.sunsun.utils.IntegerParse;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;

public class ShopCarActivity extends BaseActivity {

	List<ShopCarBean> dataList = new ArrayList<ShopCarBean>();
	ShopCarAdapter adapter;
	XListView xlistview;
	private int pageNum = 1;
	ViewGroup selectedAll;
	View delete;
	View back;
	TextView heji;
	WaitDialog dialog;
	View jiesuan;

	protected void onCreate(android.os.Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_shop_car);

		xlistview.setPullRefreshEnable(true);
		xlistview.setPullLoadEnable(true);
		xlistview.setXListViewListener(new MyXlistenr());
		adapter = new ShopCarAdapter(getApplication(), dataList, this);
		xlistview.setAdapter(adapter);
		
		setListener();

	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		pullDown();
		heji.setText("￥" +0.00);
		heji.setTag(0);
		selectedAll.setSelected(false);
	}

	private void setListener() {
		// TODO Auto-generated method stub
		selectedAll.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				v.setSelected(!v.isSelected());
				if (v.isSelected()) {
					v.setSelected(true);
					for (ShopCarBean bean : dataList) {
						bean.setSelected(true);
					}
				} else {
					v.setSelected(false);
					for (ShopCarBean bean : dataList) {
						bean.setSelected(false);
					}
				}

				notifySelectedViewState(v.isSelected());
				calculatePrice();
			}
		});

		delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				List<String> selectIds = new ArrayList<String>();
				for (ShopCarBean bean : dataList) {
					if (bean.isSelected()) {
						selectIds.add(bean.getId());
					}
				}
				if (selectIds.size() == 0) {
					return;
				}
				StringBuilder stringBuilder=new StringBuilder();
				stringBuilder.append(selectIds.get(0));
				for (int i = 1; i < selectIds.size(); i++) {
					stringBuilder.append(",").append(selectIds.get(i));
				}
				MyJsonRequest<String> request = new MyJsonRequest.Builder<String>().apiVer("100")
						.typeKey("BY_ShoppingCart_delete").param("id", stringBuilder.toString())
						.requestListener(new XRequestListener<String>() {

							@Override
							public void onResponse(String arg0) {
								Iterator<ShopCarBean> itr = dataList.iterator();

								while (itr.hasNext()) {
									ShopCarBean bean = itr.next();
									if (bean.isSelected()) {
										itr.remove();
									}
								}
								
								/*if (dialog != null) {
									dialog.dismiss();
								}*/
								
								
								
								adapter.notifyDataSetChanged();
								Toast.makeText(getApplicationContext(), arg0, 1).show();
							}
						}).errorListener(new XErrorListener() {

							@Override
							public void onErrorResponse(Exception exception, int code, String msg) {
								if (dialog != null) {
									dialog.dismiss();
								}
								Toast.makeText(getApplicationContext(), "删除失败", 1).show();
							}
						}).build();

				if (dialog == null) {
					dialog = new WaitDialog();
				}
//				dialog.show(getSupportFragmentManager(), null);

				HttpRequest.getDefaultRequestQueue().add(request);
			}
		});

		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		jiesuan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				queryCountAndBuy();
			}
		});

		xlistview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				ShopCarBean carBean = dataList.get(position - 1);

				 Intent intent=new Intent(getApplicationContext(),  GoodDetailActivity.class);
				 intent.putExtra("what", carBean.getpId());
				  
				 startActivity(intent);
			}
		});
	}

	protected void queryCountAndBuy() {
		List<String> ids = new ArrayList<String>();
		List<String> counts = new ArrayList<String>();
		
		for (ShopCarBean bean : dataList) {
			ids.add(bean.getId());
			counts.add(bean.getCount());
		}
		StringBuilder idsBuilder=new StringBuilder();
		StringBuilder countsBuilder=new StringBuilder();
		
		if (ids.size()>0) {
			idsBuilder.append(ids.get(0));
			countsBuilder.append(counts.get(0));
		}
		
		for (int i = 1; i < ids.size(); i++) {
			idsBuilder.append(",").append(ids.get(i));
			countsBuilder.append(",").append(counts.get(i));
		}
		
		MyJsonRequest<String> request = new MyJsonRequest.Builder<String>().apiVer("100")
				.typeKey("BY_ShoppingCart_edit")
				.param("id", idsBuilder.toString())
				.param("count", countsBuilder.toString())
				.requestListener(new XRequestListener<String>() {

					@Override
					public void onResponse(String arg0) {
						if (dialog != null) {
							dialog.dismiss();
						}
						ArrayList<ShopCarBean> list = new ArrayList<ShopCarBean>();
						for (ShopCarBean  shopCarBean: dataList) {
							if (shopCarBean.isSelected()) {
								list.add(shopCarBean);
							}
						}
						if (list.size()==0) {
							return;
						}
						Intent intent=new Intent(getApplicationContext(), QueRenDingDan.class);
						intent.putExtra("from", 1);
						 
						intent.putExtra("list", list);
						intent.putExtra("price",((String) heji.getTag()));
						startActivity(intent);
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code, String msg) {
						if (dialog != null) {
							dialog.dismiss();
						}
					}
				}).build();
		if (dialog == null) {
			dialog = new WaitDialog();
		}
		dialog.show(getSupportFragmentManager(), null);

		HttpRequest.getDefaultRequestQueue().add(request);
	}

	protected void notifySelectedViewState(boolean b) {
		int count = xlistview.getChildCount();
		for (int i = 0; i < count; i++) {
			try {
				View v = xlistview.getChildAt(i).findViewById(R.id.isSelected);
				v.setSelected(b);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	class MyXlistenr implements IXListViewListener {

		@Override
		public void onRefresh() {
			pullDown();
		}

		@Override
		public void onLoadMore() {
			pullUp();
		}

	}

	protected void pullDown() {
		pageNum = 1;
		MyJsonRequest.Builder<List<ShopCarBean>> builder = new MyJsonRequest.Builder<List<ShopCarBean>>().apiVer("100")
				.typeKey("BY_ShoppingCart_query")
				.param("uid", (String) SPUtils.get(getApplicationContext(), null, SPContants.USER_ID, ""))
				.param("page_no", "" + pageNum)

				.requestListener(new XRequestListener<List<ShopCarBean>>() {

					@Override
					public void onResponse(List<ShopCarBean> arg0) {
						dataList.clear();
						dataList.addAll(arg0);
						adapter.notifyDataSetChanged();
						pageNum++;
						xlistview.stopRefresh();
						
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code, String msg) {
						dataList.clear();
						adapter.notifyDataSetChanged();
						xlistview.stopRefresh();
					}
				});

		MyJsonRequest<List<ShopCarBean>> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	protected void pullUp() {
		MyJsonRequest.Builder<List<ShopCarBean>> builder = new MyJsonRequest.Builder<List<ShopCarBean>>().apiVer("100")
				.typeKey("BY_ShoppingCart_query")
				.param("uid", (String) SPUtils.get(getApplicationContext(), null, SPContants.USER_ID, ""))
				.param("page_no", "" + pageNum)

				.requestListener(new XRequestListener<List<ShopCarBean>>() {

					@Override
					public void onResponse(List<ShopCarBean> arg0) {
						dataList.addAll(arg0);
						adapter.notifyDataSetChanged();
						pageNum++;
						xlistview.stopLoadMore();
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code, String msg) {
						xlistview.stopLoadMore();
					}
				});

		MyJsonRequest<List<ShopCarBean>> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	public void calculatePrice() {
		double sum = 0;
		int count = 0;
		for (ShopCarBean bean : dataList) {
			if (bean.isSelected()) {
				count++;
				sum = sum + IntegerParse.parse(bean.getCount(), 0) * DoubleParse.parse(bean.getPrice(), 0);
			}
		}
		String p= String.format("%.2f", sum);
		heji.setText("￥" +p);
		heji.setTag(p);
		if (count == dataList.size() && count != 0) {

			selectedAll.setSelected(true);

		} else {
			selectedAll.setSelected(false);

		}

	}
}
